import { useState, useEffect, useRef } from "react"
import { Select, Button, Modal, message, Spin } from 'antd'
import { ExclamationCircleFilled } from '@ant-design/icons'
import style from './index.module.less'
import Editor from '../Editor'
import { getTemplateDetail, getTemplateList } from '@/services/template'
import type { TemplateList } from '@/interfaces/template'
import FingerInput from "../FingerInput"
import { STATUS_CODE } from '@/common/const'
type Props = {
    id: string
    onSave: () => void
    saveApi: (any) => Promise<any>
    type: 'mz' | 'zy'
}
export default (props: Props) => {
    const { id, onSave, saveApi, type } = props
    const editorRef = useRef<any>(null)
    const [template, setTemplate] = useState()
    const [loading, setLoading] = useState(false)
    const [html, setHtml] = useState('')
    const [templateData, setTemplateData] = useState<TemplateList[]>([])
    const [fingerUrl, setFingerUrl] = useState('')
    const [htmlLoading, setHtmlLoading] = useState(false)

    useEffect(() => {
        getTemplateList({ recordId: id, type }).then(res => {
            setTemplateData(res?.dataList || [])
        })
    }, [])

    const getHTMLDetail = (val) => {
        setHtmlLoading(true)
        getTemplateDetail({ templateId: val, recordId: id }).then(({ data }) => {
            setHtml(data.content)
        }).finally(() => {
            setHtmlLoading(false)
        })
    }

    const handleChange = async (val) => {
        if (template) {
            Modal.confirm({
                title: '切换模板',
                icon: <ExclamationCircleFilled />,
                content: '切换模板后，未保存内容将会消失，确认切换模板？',
                onOk() {
                    setTemplate(val);
                    // 请求接口
                    getHTMLDetail(val)
                },
                onCancel() {
                    console.log('Cancel');
                },
            })
        } else {
            setTemplate(val)
            getHTMLDetail(val)
        }

    }

    const handleSave = async () => {
        const html = editorRef.current?.getHtml();
        // 暂时去掉指纹限制
        // if (!fingerUrl) {
        //     message.error('未录入患者指纹')
        //     return;
        // }
        try {
            setLoading(true)
            const result = await saveApi({ content: html, signature: fingerUrl, recordId: id, templateId: template })
            if (result.code === STATUS_CODE.SUCCESS) {
                message.success('保存成功')
                onSave();
            } else {
                message.error(result.message);
            }
        } catch (error) {
            message.error('保存失败')
        } finally {
            setLoading(false);
        }
    }

    const handleFinishInput = (url) => {
        setFingerUrl(url)
    }
    return (
        <div className={style.addMedical}>
            <div className={style.form}> <div className="label">病历模板：</div>
                <Select
                    onChange={handleChange}
                    style={{ width: 200 }}
                    value={template}
                    placeholder="请选择病例模版"
                    options={templateData.map(item => {
                        return {
                            value: item.templateId,
                            label: item.name
                        }
                    })}
                /></div>
            <div className={style.content}>
                <Spin spinning={htmlLoading}>
                    <Editor content={html} ref={editorRef} readonly={false} />
                </Spin>
            </div>
            {fingerUrl ? <div className={style.finger}>
                患者指纹：
                <img src={fingerUrl} alt="" />
            </div> : null}

            <div className={style.button}>
                <FingerInput onFinish={handleFinishInput} />
                <Button type="primary" onClick={handleSave} loading={loading}>保存病历</Button>
            </div>
        </div>
    )
}